package org.jeecg.modules.water.service.impl;



import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import okhttp3.*;
import org.jeecg.modules.water.entity.LwgyJointWater;
import org.jeecg.modules.water.entity.LwgyJointWaterCmd;
import org.jeecg.modules.water.entity.LwgyJointWaterConfiguration;
import org.jeecg.modules.water.mapper.LwgyJointWaterMapper;
import org.jeecg.modules.water.service.ILwgyJointWaterService;
import org.jeecg.modules.water.service.ILwgyRelaxConnectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
//轻松表计对接（电信运营商接口）
public class LwgyRelaxConnectionServiceImpl extends ServiceImpl<LwgyJointWaterMapper, LwgyJointWater> implements ILwgyRelaxConnectionService {

    public static String URL="http://meter-api.ucn.plus";
    public static String OPENID="02718b89709a48dc9ffdcb6c9210b3ca";
    public static String DEVICECODE="00005386";//采集器010020180017 设备編码 00005386
    public static String USERCODE="00005386";//第三方用户编码

    public static String OPENORCLOSEURL="/open/openapi/valve/";//开关阀
    public static String READRECORDURL="/open/openapi/read/record/";//读取设备历史纪录数据
    public static String READINFOPAGEURL="/open/openapi/read/info/page/";//分页读取设备信息

    @Autowired
    private ILwgyJointWaterService lwgyJointWaterService;



    public String getOAuthToken(){
        try{
            OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
            MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
            RequestBody body = RequestBody.create(mediaType, "");
            Request request = new Request.Builder()
                    .url(URL+"/auth/oauth/token?grant_type=client_credentials&scope=open")
                    .method("POST", body)
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .addHeader("Authorization", "Basic b3BlbmNsaWVudDpvcGVuY2xpZW50")
                    .build();
            Response response = client.newCall(request).execute();
            if(response.isSuccessful()){
                ObjectMapper objectMapper = new ObjectMapper();
                String jsonResponse  = response.body().string();
                Map<String, String> data = objectMapper.readValue(jsonResponse, new TypeReference<HashMap<String, String>>() {});
                return  data.get("access_token");
            }else{
                return null;
            }
        }catch (Exception e){
            System.out.println("调用轻松表计鉴权接口报错");
            return null;
        }

    }

    public String ReadDeviceInformation(LwgyJointWaterConfiguration lwgyJointWaterConfiguration){
        //http://meter-api.ucn.plus/open/openapi/read/info/02718b89709a48dc9ffdcb6c9210b3ca/010020180017
        try{
            String token=getOAuthToken();
            String number=lwgyJointWaterConfiguration.getDeviceNumber();
            System.out.println("token"+token);
            String authorization ="Bearer "+token;
            System.out.println("Authorization"+authorization);
            System.out.println("URL"+URL+"/open/openapi/read/info/"+OPENID+"/"+number);
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            Request request = new Request.Builder()
                    .url(URL+"/open/openapi/read/info/"+OPENID+"/"+number)
                    .get()
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .addHeader("Authorization", authorization)
                    .build();
            Response response = client.newCall(request).execute();
            String jsonString = response.body().string();
            return jsonString;
        /*    if(response.isSuccessful()) {*/

                /*JSONObject json = JSONObject.fromObject(jsonString);
                String code = json.getString("code");
                if ("0".equals(code)) {
                    JSONObject data = json.getJSONObject("data");
//                    String id = data.getString("id");
                    JSONObject extendDict = data.getJSONObject("extendDict");
                    String deviceTypeCode = extendDict.getString("deviceTypeCode");
                    String deviceClock = extendDict.getString("deviceClock");
                    String updateTime = extendDict.getString("updateTime");
                    String deviceCode = extendDict.getString("deviceCode");
                    int deviceRSSI = extendDict.getInt("deviceRSSI");
                    int deviceBuyTimes = extendDict.getInt("deviceBuyTimes");
                    double deviceVoltage = extendDict.getDouble("deviceVoltage");
                    int valveStatus = extendDict.getInt("valveStatus");
                    int feeStatus = extendDict.getInt("feeStatus");
                    int voltageStatus = extendDict.getInt("voltageStatus");
                    int deviceCurrentData = extendDict.getInt("deviceCurrentData");
                    int deviceLastData = extendDict.getInt("deviceLastData");
                    int deviceSettleDay = extendDict.getInt("deviceSettleDay");
                    int deviceSettleDayData = extendDict.getInt("deviceSettleDayData");
                    int deviceBalance = extendDict.getInt("deviceBalance");
                    int deviceTotalData = extendDict.getInt("deviceTotalData");
                    String deviceUserName = extendDict.getString("deviceUserName");
                    String deviceAddress = extendDict.getString("deviceAddress");
                    System.out.println("json"+data);*/
                    /**
                     * {
                     *     "code": 0,
                     *     "msg": null,
                     *     "data": {
                     *         "extendDict": {
                     *             "deviceTypeCode": "SBHB",
                     *             "deviceClock": "2024-01-28 09:11:26",//设备时钟
                     *             "updateTime": "2024-01-30 01:00:07",//数据抄收时间
                     *             "deviceCode": "00005386",
                     *             "deviceRSSI": 65,//	信号强度
                     *             "deviceBuyTimes": 2,
                     *             "deviceVoltage": 3.54,//电池电压
                     *             "deviceStatus": "",
                     *             "valveStatus": 1,
                     *             "feeStatus": 0,
                     *             "voltageStatus": 0,
                     *             "deviceCurrentData": 0,
                     *             "deviceLastData": 75,
                     *             "deviceSettleDay": 31,
                     *             "deviceSettleDayData": 75,
                     *             "deviceBalance": 1990,//设备余额
                     *             "deviceTotalData": 100,//设备累计流量
                     *             "externalCode": null,
                     *             "deviceUserName": "张三",//设备所属用户名称
                     *             "deviceAddress": "山东省/泰安市/泰山区/金凤嘉苑/一号楼/101"//设备用户地址
                     *         },
                     *         "responseCode": 0,
                     *         "responseInfo": "读取正常"
                     *     }
                     * }
                     * */
               /* }*/

       /*     }

            return null;*/
        }catch (Exception e){
            System.out.println("调用轻松表 计读取设备信息接口报错"+e);
            return  null;

        }
    }

//    public void BatchReadDeviceInformation(){
//        //http://meter-api.ucn.plus/open/openapi/read/info/02718b89709a48dc9ffdcb6c9210b3ca/010020180017
//        try{
//            String token=getOAuthToken();
//            String authorization ="Bearer "+token;
//            int pageNumber = 1; // 当前页码
//            int pageSize = 50; // 每页显示条目数量
//            while (! BatchSaveDevice(authorization,pageNumber,pageSize)){
//                BatchSaveDevice(authorization,pageNumber+1,pageSize);
//            }
//        }catch (Exception e){
//            System.out.println("调用轻松表计读取设备信息接口报错"+e);
//
//        }
//    }
    public void BatchReadDeviceInformation() {
        try {
            String token = getOAuthToken();
            String authorization = "Bearer " + token;
            int pageNumber = 1; // 当前页码
            int pageSize = 50; // 每页显示条目数量

            while (true) {
                boolean success = BatchSaveDevice(authorization, pageNumber, pageSize);
                if (!success) {
                    break; // 如果批量保存失败，则跳出循环
                }
                pageNumber++; // 增加页码
            }
        } catch (Exception e) {
            System.out.println("调用轻松表计读取设备信息接口报错" + e);
        }
    }
    public boolean BatchSaveDevice(String authorization,int pageNumber,int pageSize) throws IOException {
        try {
            String urls = URL + READINFOPAGEURL + OPENID + "?current=" + pageNumber + "&size=" + pageSize;
            System.out.println("URL" + urls);
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            Request request = new Request.Builder()
                    .url(urls)
                    .get()
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .addHeader("Authorization", authorization)
                    .build();
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {

                String jsonString = response.body().string();
                JSONObject json = JSONObject.fromObject(jsonString);
                String code = json.getString("code");

                if ("0".equals(code)) {
                    JSONObject data = json.getJSONObject("data");
                    int current = data.getInt("current");//当前页
                    System.out.println("data:" + current);
                    int pages = data.getInt("pages");//总页数
                    System.out.println("data:" + pages);
                    JSONArray records = data.getJSONArray("records");
                    List<LwgyJointWater> list = new ArrayList();

                    for (int i = 0; i < records.size(); i++) {
                        LwgyJointWater water = new LwgyJointWater();
                        JSONObject recordsData = records.getJSONObject(i);
                        String deviceCode = recordsData.getString("deviceCode");//设备编码(表号)
                        String deviceTypeCode = recordsData.getString("deviceTypeCode");//设备类型？不知道
                        String deviceClock = recordsData.getString("deviceClock");//设备时钟
                        String updateTime = recordsData.getString("updateTime");//数据抄收时间
                        String deviceRSSI = recordsData.getString("deviceRSSI");//信号强度
                        // String deviceBuyTimes = recordsData.getString("deviceBuyTimes");//购买次数(这些是lora表存在nb不存在，后期可能要添加，先不删除)
                        //String deviceVoltage = recordsData.getString("deviceVoltage");//电池电压 float
                       // String deviceBalance = recordsData.getString("deviceBalance");//设备余额  long
                        String deviceTotalData = recordsData.getString("deviceTotalData");//设备累计流量
                       // String deviceSettleDayData = recordsData.getString("deviceSettleDayData");//结算日流量
                       // String deviceSettleDay = recordsData.getString("deviceSettleDay");//结算日
                       // String deviceCurrentData = recordsData.getString("deviceCurrentData");//瞬时流量
                       // String deviceLastData = recordsData.getString("deviceLastData");//上月使用流量
                        String valveStatus = recordsData.getString("valveStatus");//阀门状态
                        String voltageStatus = recordsData.getString("voltageStatus");//电池状态
                       // String feeStatus = recordsData.getString("feeStatus");//表端预付费费用状态



                        water.setIspid(deviceCode);
                        water.setCurtime(updateTime);//抄表时间
                        // water.setStationcode();//分站号（这些是nb表有lora表不存在的）
                        water.setCurnum(String.valueOf(Double.parseDouble(deviceTotalData)/1000));//当前读数
                        //nb：阀门状态 02未知 00开 01关 10无阀 11异常
                        //lora：int 0 无阀控 1开-合 2 关-断 3 异常 4 漏气 5 比率开阀
                        water.setValvestate(valveStatus);//阀门状态
                        water.setBattery(voltageStatus);//电池状态
                        //water.setSensor();//传感器状态
                        water.setSignalstrength(deviceRSSI);//信号强度值
                        //water.setReadperiod();//抄表周期
                        water.setMeterReadingType("0");//自动抄表
                        list.add(water);
                    }
                    lwgyJointWaterService.saveBatch(list);


                    if (current < pages) {//当前页<总页数，说明还有下一些
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }catch (Exception e){
            System.out.println("e"+e);
            return false;
        }
    }

    public void getUserDeviceInformation(){
        try{
            String token=getOAuthToken();
            String authorization ="Bearer "+token;

            OkHttpClient client = new OkHttpClient().newBuilder().build();
            Request request = new Request.Builder()
                    .url(URL + "/open/openapi/read/userdevice/" + OPENID + "/" + USERCODE)
                    .get()
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .addHeader("Authorization", authorization)
                    .build();
            Response response = client.newCall(request).execute();
            if(response.isSuccessful()) {
                String jsonString = response.body().string();
                JSONObject json = JSONObject.fromObject(jsonString);
                int code = json.getInt("code");
                if (code == 0) {
                    JSONObject data = json.getJSONObject("data");
                    String deviceCode = data.getString("deviceCode");
                    String deviceClock = data.getString("deviceClock");
                    int deviceRSSI = data.getInt("deviceRSSI");
                    int deviceBuyTimes = data.getInt("deviceBuyTimes");
                    int deviceVoltage = data.getInt("deviceVoltage");
                    String deviceCurrentData= data.getString("deviceCurrentData");
                    String deviceSettleDay = data.getString("deviceSettleDay");
                    String deviceSettleDayData = data.getString("deviceSettleDayData");
                    int deviceBalance = data.getInt("deviceBalance");
                    String deviceTotalData = data.getString("deviceTotalData");
                    String deviceLastData = data.getString("deviceLastData");
                    String valveStatus = data.getString("valveStatus");
                    String voltageStatus = data.getString("voltageStatus");
                    String feeStatus = data.getString("feeStatus");
                    String deviceAddress = data.getString("deviceAddress");
                    String deviceUserName =  data.getString("deviceUserName");
                } else {
                    System.out.println("Error message: " + json.getString("msg"));
                }
            } else {
                System.out.println("Request failed with code: " + response.code());
            }
        }catch (Exception e){
            System.out.println("调用轻松表计根据外部用户编码获取用户设备信息接口报错"+e);
        }
    }

    public void updateExternalCode(String deviceCode, String externalCode){
        try{
            String token=getOAuthToken();
            String authorization ="Bearer "+token;
            OkHttpClient client = new OkHttpClient().newBuilder().build();

            MediaType mediaType = MediaType.parse("application/json");
            JSONObject requestBody = new JSONObject();
            requestBody.put("deviceCode", deviceCode);
            requestBody.put("externalCode", externalCode);
            RequestBody body = RequestBody.create(mediaType,requestBody.toString());

            Request request = new Request.Builder()
                    .url(URL+"/open/openapi/user/externalcode/"+OPENID+"/"+DEVICECODE).put(body)
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .addHeader("Authorization", authorization).build();
            Response response = client.newCall(request).execute();
            if(response.isSuccessful()) {
                String jsonString = response.body().string();
                JSONObject json = JSONObject.fromObject(jsonString);
                int code = json.getInt("code");
                if (code == 0) {
                    System.out.println("更新成功!");
                } else {
                    System.out.println("Error message: " + json.getString("msg"));
                }
            } else {
                System.out.println("Request failed with code: " + response.code());
            }
        }catch (Exception e){
            System.out.println("调用轻松表计更新外部编码接口报错"+e);

        }
    }

    public String OpenOrCloseDevice(LwgyJointWaterCmd lwgyJointWaterCmd){
        try {
            String token = getOAuthToken();
            String authorization = "Bearer" + token;

            OkHttpClient client = new OkHttpClient().newBuilder().build();

          /*  JSONArray dataArray = new JSONArray();*/
            JSONObject dataObject = new JSONObject();
         /*    dataObject.put("openId",OPENID);//公司ID
            dataObject.put("deviceCode",lwgyJointWaterCmd.getIspid());// 设备编码(表地址、表号)*/
            dataObject.put("valveStatus",Integer.parseInt(lwgyJointWaterCmd.getType()));// 1 开阀 2 关阀
        /*    dataArray.add(dataObject);
            String requestBody = dataArray.toString();*/
            String requestBody =dataObject.toString();
            System.out.println("======requestBody"+requestBody);
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType,requestBody);
            Request request = new Request.Builder()
                    .url(URL + OPENORCLOSEURL+OPENID+"/"+lwgyJointWaterCmd.getIspid()+"?valveStatus="+Integer.parseInt(lwgyJointWaterCmd.getType()))
                    .post(body)
                    .addHeader("Content-Type", "*")//application/x-www-form-urlencoded
                    .addHeader("Authorization", authorization)
                    .build();

            Response response = client.newCall(request).execute();
            System.out.println("======response.isSuccessful()"+response.isSuccessful());
            if(response.isSuccessful()){
                String jsonString = response.body().string();
                System.out.println("======jsonString"+jsonString);
                return jsonString;
            }
            System.out.println("======lwgyJointWaterCmd.getIspid()"+lwgyJointWaterCmd.getIspid()+":"+lwgyJointWaterCmd.getType());
            System.out.println("======request"+request);
            System.out.println("======url"+URL + OPENORCLOSEURL+OPENID+"/"+lwgyJointWaterCmd.getIspid());
            System.out.println("======body"+body);


            return null;


            /*if (response.isSuccessful()){
                String jsonString = response.body().string();
                JSONObject json = JSONObject.fromObject(jsonString);
                int code = json.getInt("code");
                if (code == 0){
                    System.out.println("成功了哈");
                }else {
                    System.out.println("不太行"+json.getString("msg"));
                }

            }else {
                System.out.println("错误码"+response.code());
            }*/
        }catch (Exception e){
            System.out.println("调用轻松表计接口报错"+e);
            return null;

        }
    }


    public void uploadDeviceData() {
        try {
            String token = getOAuthToken();
            String authorization = "Bearer " + token;

            OkHttpClient client = new OkHttpClient().newBuilder().build();

            // 构造JSON数组，并转换为字符串
            JSONArray dataArray = new JSONArray();
            JSONObject dataObject = new JSONObject();
            dataObject.put("factoryCode", "");
            dataObject.put("deviceType", 1);
            dataObject.put("deviceCode", "001");
            dataObject.put("deviceClock", "2022-03-01 12:00:00");
            dataObject.put("updateTime", "2022-03-01 12:00:00");
            dataObject.put("deviceRSSI", 100);
            dataObject.put("deviceVoltage", "3.18");
            dataObject.put("deviceCurrentData", 10);
            dataObject.put("deviceSettleDayData", 20);
            dataObject.put("deviceTotalData", 30);
            dataObject.put("deviceLastData", 40);
            dataObject.put("valveStatus", 1);
            dataObject.put("voltageStatus", 0);
            dataArray.add(dataObject);
            String requestBody = dataArray.toString();

            RequestBody body = RequestBody.create(MediaType.parse("*/*"), requestBody);

            Request request = new Request.Builder()
                    .url(URL + "/open/openapi/data/upload/" + OPENID + "/")
                    .post(body)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Authorization", authorization)
                    .build();

            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                String jsonString = response.body().string();
                JSONObject json = JSONObject.fromObject(jsonString);
                int code = json.getInt("code");
                if (code == 0) {
                    JSONObject data = json.getJSONObject("data");
                    JSONArray valveTaskArray = data.getJSONArray("valveTask");
                    for (int i = 0; i < valveTaskArray.size(); i++) {
                        JSONObject valveTask = valveTaskArray.getJSONObject(i);
                        int valveStatus = valveTask.getInt("valveStatus");
                        String deviceCode = valveTask.getString("deviceCode");
                        System.out.println("valveStatus And deviceCode " + deviceCode + ": " + valveStatus);
                    }
                } else {
                    System.out.println("Error message: " + json.getString("msg"));
                }
            } else {
                System.out.println("Request failed with code: " + response.code());
            }
        }catch (Exception e){
            System.out.println("调用轻松表计第三方设备数据上传接口报错"+e);
        }

    }


    public String getMessages(String ispid,String begintime,String endtime){
        try {
            String token = getOAuthToken();
            String authorization = "Bearer" + token;

            OkHttpClient client = new OkHttpClient().newBuilder().build();

            JSONArray dataArray = new JSONArray();
            JSONObject dataObject = new JSONObject();
            dataObject.put("openId",OPENID);//公司ID
            dataObject.put("deviceCode",ispid);// 设备编码(表地址、表号)
            //dataObject.put("current",lwgyJointWaterCmd.getType());// 	当前页
            //dataObject.put("size",lwgyJointWaterCmd.getType());// 每页记录数(最大50)
            //dataObject.put("startTime",lwgyJointWaterCmd.getType());// 查询记录开始时间(格式:yyyy-MM-dd HH:mm:ss)
           // dataObject.put("endTime",lwgyJointWaterCmd.getType());//查询记录结束时间(格式:yyyy-MM-dd HH:mm:ss)
            dataArray.add(dataObject);
            String requestBody = dataArray.toString();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType,requestBody);
            Request request = new Request.Builder()
                    .url(URL + READRECORDURL+OPENID+"/"+ispid)
                    .post(body)
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .addHeader("Authorization", authorization)
                    .build();

            Response response = client.newCall(request).execute();
            System.out.println("======request"+request);
            System.out.println("======url"+URL + OPENID+OPENID+"/"+ispid);
            System.out.println("======dataArray"+dataArray);
            System.out.println("======response"+response.body().string());
            return response.body().string();
            /*if (response.isSuccessful()){
                String jsonString = response.body().string();
                JSONObject json = JSONObject.fromObject(jsonString);
                int code = json.getInt("code");
                if (code == 0){
                    System.out.println("成功了哈");
                }else {
                    System.out.println("不太行"+json.getString("msg"));
                }

            }else {
                System.out.println("错误码"+response.code());
            }*/
        }catch (Exception e){
            System.out.println("调用轻松表计接口报错");
            return null;

        }
    }
    public static void main(String[] args){
        LwgyRelaxConnectionServiceImpl a = new LwgyRelaxConnectionServiceImpl();
        //a.getOAuthToken();
//        a.ReadDeviceInformation();
        a.BatchReadDeviceInformation();
//        a.getUserDeviceInformation();
//        a.uploadDeviceData();
//        a.OpenOrCloseDevice();
    }
}
